package com.whfc.wxmp.interceptor;

import com.whfc.common.exception.BizException;
import com.whfc.common.result.ResultEnum;
import com.whfc.common.util.SessionAttr;
import com.whfc.wxmp.annotation.CurrentWxUser;
import com.whfc.fuum.entity.SysUser;
import com.whfc.fuum.entity.WxUser;
import com.whfc.fuum.service.SysUserService;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author xuguocheng
 * @desc 拦截器, 一些接口必须注册才能访问.
 * @date 2019-08-03
 */
@Component
public class WxUserIntercepter implements HandlerInterceptor {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @DubboReference(interfaceClass = SysUserService.class, version = "1.0.0")
    private SysUserService sysUserService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        logger.debug("preHandle,uri:{}", request.getRequestURI());
        Session session = SecurityUtils.getSubject().getSession();
        WxUser wxUser = (WxUser) session.getAttribute(SessionAttr.WXMP_USER);
        if (wxUser == null) {
            throw new BizException(ResultEnum.FAILURE.getCode(), "该用户不存在.");
        }
        SysUser sysUser = (SysUser) session.getAttribute(SessionAttr.MS_USER);
        if (sysUser == null) {
            sysUser = sysUserService.getUserByPhone(wxUser.getPhone());
            if (sysUser != null) {
                session.setAttribute(SessionAttr.MS_USER, sysUser);
            }
        }
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        logger.debug("postHandle,uri:{}", request.getRequestURI());
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        logger.debug("afterCompletion,uri:{}", request.getRequestURI());
    }
}
